package com.codeest.geeknews.util;

import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;

import wseemann.media.FFmpegMediaMetadataRetriever;

import static com.codeest.geeknews.ui.main.activity.PhotoDetailActivity.bitmap;

public class VideoUtil {

    /**
     * 保存视频缩略图
     *
     * @throws IOException
     */
    public static void saveVideoThumbnail(String videoPath, String imagePath) throws IOException {
        //ffmpeg -i xxx.mp4 -y -f image2 -t 0.001 -s 125x125 xxx.jpg
        List<String> cmd = new java.util.ArrayList<String>();
        cmd.add("ffmpeg");// 视频提取工具的位置
        cmd.add("-i");
        cmd.add(videoPath);
        cmd.add("-y");
        cmd.add("-f");
        cmd.add("image2");
        cmd.add("-t");
        cmd.add("0.001");
        cmd.add("-s");
        cmd.add("125x125");
        cmd.add(imagePath);
        ProcessBuilder builder = new ProcessBuilder();
        builder.command(cmd);
        builder.start();
    }


//    public static void main(String[] args) {
//
//        String result = processFLV("20150722190602BmEf1C9Z.mp4");
//
//        PatternCompiler compiler = new Perl5Compiler();
//        try {
//            String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
//            String regexVideo = "Video: (.*?), (.*?), (.*?)[,\\s]";
//            String regexAudio = "Audio: (\\w*), (\\d*) Hz";
//
//            Pattern patternDuration = compiler.compile(regexDuration, Perl5Compiler.CASE_INSENSITIVE_MASK);
//            PatternMatcher matcherDuration = new Perl5Matcher();
//            if (matcherDuration.contains(result, patternDuration)) {
//                MatchResult re = matcherDuration.getMatch();
//
//                System.out.println("提取出播放时间  ===" + re.group(1));
//                System.out.println("开始时间        =====" + re.group(2));
//                System.out.println("bitrate 码率 单位 kb==" + re.group(3));
//            }
//
//            Pattern patternVideo = compiler.compile(regexVideo, Perl5Compiler.CASE_INSENSITIVE_MASK);
//            org.apache.oro.text.regex.PatternMatcher matcherVideo = new Perl5Matcher();
//
//            if (matcherVideo.contains(result, patternVideo)) {
//                MatchResult re = matcherVideo.getMatch();
//                System.out.println("编码格式  ===" + re.group(1));
//                System.out.println("视频格式 ===" + re.group(2));
//                System.out.println("分辨率  ==" + re.group(3));
//            }
//
//            Pattern patternAudio = compiler.compile(regexAudio,
//                    Perl5Compiler.CASE_INSENSITIVE_MASK);
//            PatternMatcher matcherAudio = new Perl5Matcher();
//
//            if (matcherAudio.contains(result, patternAudio)) {
//                MatchResult re = matcherAudio.getMatch();
//                System.out.println("音频编码             ===" + re.group(1));
//                System.out.println("音频采样频率  ===" + re.group(2));
//            }
//
//        } catch (MalformedPatternException e) {
//            e.printStackTrace();
//        }
//
//    }

    // ffmpeg能解析的格式：（asx，asf，mpg，wmv，3gp，mp4，mov，avi，flv等）
    private static String processFLV(String inputPath) {
        List<String> commend = new java.util.ArrayList<String>();
        // commend.add("e:\\videoconver\\ffmpeg\\ffmpeg ");//可以设置环境变量从而省去这行
        commend.add("ffmpeg");
        commend.add("-i");
        commend.add(inputPath);

        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commend);
            builder.redirectErrorStream(true);
            Process p = builder.start();

            // 1. start
            // 保存ffmpeg的输出结果流
            BufferedReader buf = null;
            String line = null;
            // read the standard output

            buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuffer sb = new StringBuffer();
            while ((line = buf.readLine()) != null) {
                sb.append(line);
                continue;
            }

            // 这里线程阻塞，将等待外部转换进程运行成功运行结束后，才往下执行
            @SuppressWarnings("unused")
            int ret = p.waitFor();
            // 1. end
            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }

    public static int getDuration(String url) {
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepare();
            return mediaPlayer.getDuration();
        } catch (IOException e) {
            e.printStackTrace();
        }/* finally {
            mediaPlayer.release();
        }*/
        return 0;

    }

    public interface Callback {
        /**
         * 获取时长
         * duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);
         * Long.parseLong(duration)
         * 获取Metadata(album/artist/...)
         * mmr.getMetadata()
         */
        void onMetadata(FFmpegMediaMetadataRetriever mmr);

    }

    public static void getMetadata(final String url, final Callback callback) {
        Log.i("VideoUtil", "getMetadata url=" + url);
        new Thread(new Runnable() {
            @Override
            public void run() {
//                String duration = null;
//                android.media.MediaMetadataRetriever mmr = new android.media.MediaMetadataRetriever();
                FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
                try {
                    if (url != null) {
                        HashMap<String, String> headers = null;
                        if (headers == null) {
                            headers = new HashMap<String, String>();
                            headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
                            headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.1.1; zh-cn; SAMSUNG-GT-N7108_TD/1.0 Android/4.1.1 Release/08.30.2012 Browser/AppleWebKit534.30 Build/JRO03C) ApplelWebkit/534.30 (KHTML,like Gecko) Version/4.0 Mobile Safari/534.30");
                            headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.2.2; zh-cn; RLT Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 ");
                            headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-cn; MI 3C Build/KVT49L) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Mobile Safari/537.36 XiaoMi/MiuiBrowser/2.0.1");
                        }
                        mmr.setDataSource(url, headers);
                    }
                    //duration = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION);
                    //mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ALBUM);
                    //mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ARTIST);
                    callback.onMetadata(mmr);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    reGetMetadata(url, callback);//FFmpegMediaMetadataRetriever setDataSource failed: status = 0xFFFFFFFF,重新获取一一次就好了
                } finally {
                    mmr.release();
                    Log.i("VideoUtil", "getMetadata released");
                }
            }
        }).start();
    }

    private static void reGetMetadata(final String url, final Callback callback) {
        Log.i("VideoUtil", "getMetadata url=" + url);
        new Thread(new Runnable() {
            @Override
            public void run() {
//                String duration = null;
//                android.media.MediaMetadataRetriever mmr = new android.media.MediaMetadataRetriever();
                FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
                try {
                    if (url != null) {
                        HashMap<String, String> headers = null;
                        if (headers == null) {
                            headers = new HashMap<String, String>();
                            headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
                            headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.1.1; zh-cn; SAMSUNG-GT-N7108_TD/1.0 Android/4.1.1 Release/08.30.2012 Browser/AppleWebKit534.30 Build/JRO03C) ApplelWebkit/534.30 (KHTML,like Gecko) Version/4.0 Mobile Safari/534.30");
                            headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.2.2; zh-cn; RLT Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 ");
                            headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-cn; MI 3C Build/KVT49L) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Mobile Safari/537.36 XiaoMi/MiuiBrowser/2.0.1");
                        }
                        mmr.setDataSource(url, headers);
                    }
                    //duration = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION);
                    //mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ALBUM);
                    //mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ARTIST);
                    callback.onMetadata(mmr);
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    mmr.release();
                    Log.i("VideoUtil", "getMetadata released");
                }
            }
        }).start();
    }

    private Bitmap createVideoThumbnail(String url, int width, int height) {
        FFmpegMediaMetadataRetriever fmmr = new FFmpegMediaMetadataRetriever();
        try {
            fmmr.setDataSource(url);
            bitmap = fmmr.getFrameAtTime();
            if (bitmap != null) {
                Bitmap b2 = fmmr
                        .getFrameAtTime(
                                4000000,
                                FFmpegMediaMetadataRetriever.OPTION_CLOSEST_SYNC);
                if (b2 != null) {
                    bitmap = b2;
                }
                if (bitmap.getWidth() > 640) {// 如果图片宽度规格超过640px,则进行压缩
                    bitmap = ThumbnailUtils.extractThumbnail(bitmap,
                            640, 480,
                            ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
                }
            }
            return bitmap;
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        } finally {
            fmmr.release();
        }
        return null;
    }
}
